"""
This module demonstrates various advanced Python features, including singletons,
decorators, and enumerations, to show the flexibility of Sphinx in documenting them.
"""

from enum import Enum
from functools import wraps
import threading


class SingletonMeta(type):
    """
    A thread-safe implementation of Singleton.

    This SingletonMeta is a metaclass that ensures any class using it as
    a metaclass will only have one instance.

    Attributes:
        _instances (dict): Stores the single instance of each class.
    """

    _instances = {}
    _lock = threading.Lock()

    def __call__(cls, *args, **kwargs):
        with cls._lock:
            if cls not in cls._instances:
                instance = super().__call__(*args, **kwargs)
                cls._instances[cls] = instance
        return cls._instances[cls]


class Database(metaclass=SingletonMeta):
    """
    Database class demonstrating a singleton.

    Attributes:
        connection (str): A simulated database connection string.
    """

    def __init__(self):
        """
        Initialize the Database with a connection string.
        """
        self.connection = "Database connection established."

    def query(self, sql):
        """
        Executes a SQL query on the database.

        Args:
            sql (str): The SQL query to be executed.

        Returns:
            str: The simulated result of the SQL query.
        """
        return f"Executing '{sql}' on {self.connection}"


def log_execution(func):
    """
    A decorator that logs the execution of a function.

    Args:
        func (callable): The function to be decorated.

    Returns:
        callable: The wrapped function with added logging.
    """

    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Starting '{func.__name__}'...")
        result = func(*args, **kwargs)
        print(f"Finished '{func.__name__}'")
        return result

    return wrapper


class Status(Enum):
    """
    Status is an enumeration for tracking the state of a task.

    Attributes:
        PENDING: The task is pending.
        RUNNING: The task is currently running.
        COMPLETED: The task has been completed.
        FAILED: The task has failed.
    """

    PENDING = "Pending"
    RUNNING = "Running"
    COMPLETED = "Completed"
    FAILED = "Failed"


@log_execution
def perform_task(status):
    """
    A function that performs a task based on its status.

    Args:
        status (Status): The current status of the task.

    Raises:
        ValueError: If the status is Status.FAILED.

    Returns:
        str: A message indicating the result of the task.
    """
    if status == Status.FAILED:
        raise ValueError("The task has failed!")
    return f"The task is {status.value}."


# Example usage of the Database singleton and perform_task function
if __name__ == "__main__":
    db = Database()
    print(db.query("SELECT * FROM users"))

    try:
        print(perform_task(Status.RUNNING))
        print(perform_task(Status.COMPLETED))
    except ValueError as e:
        print(e)
